package cn.skyisazure.metacompare.sqlcompare.mysql;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.skyisazure.metacompare.metaVo.EntityDataSourceInfoVO;
import cn.skyisazure.metacompare.metaVo.EntityTableInfoVO;
import cn.skyisazure.metacompare.sqlcompare.enums.CompareScopeStrategy;
import cn.skyisazure.metacompare.sqlcompare.meta.ColumnCM;
import cn.skyisazure.metacompare.sqlcompare.meta.IndexCM;
import cn.skyisazure.metacompare.sqlcompare.meta.TableCM;
import cn.skyisazure.metacompare.sqlcompare.serivce.AbstractMetaService;
import cn.skyisazure.metacompare.sqlcompare.utils.DDLConstant;
import lombok.Data;
import lombok.NonNull;

import java.sql.SQLException;
import java.util.*;


/**
 * @author wangjj
 * @date 2023/8/18 13:39
 */
@Data
public class MysqlMetaServiceImpl extends AbstractMetaService {

    private final MysqlMetaConvert convertToBo;

    public MysqlMetaServiceImpl(@NonNull EntityDataSourceInfoVO sourceEntityDataSourceInfoVO,
                                @NonNull EntityDataSourceInfoVO targetEntityDataSourceInfoVO) {
        convertToBo = new MysqlMetaConvert(sourceEntityDataSourceInfoVO,targetEntityDataSourceInfoVO,CompareScopeStrategy.DATASOURCE);
    }

    public MysqlMetaServiceImpl(@NonNull EntityTableInfoVO sourceEntityTableInfoVO,
                                @NonNull EntityTableInfoVO targetEntityTableInfoVO) {
        EntityTableInfoVO sourceTableInfo = ObjectUtil.clone(sourceEntityTableInfoVO);
        EntityTableInfoVO targetTableInfo = ObjectUtil.clone(targetEntityTableInfoVO);
        EntityDataSourceInfoVO sourceEntityDataSourceInfoVO = new EntityDataSourceInfoVO();
        sourceEntityDataSourceInfoVO.setEntityTableInfos(Collections.singletonList(sourceTableInfo));
        EntityDataSourceInfoVO targetEntityDataSourceInfoVO = new EntityDataSourceInfoVO();
        targetEntityDataSourceInfoVO.setEntityTableInfos(Collections.singletonList(targetTableInfo));
        convertToBo = new MysqlMetaConvert(sourceEntityDataSourceInfoVO,targetEntityDataSourceInfoVO,CompareScopeStrategy.TABLE);
    }


    //=======以下是获取build语句=============
    // =============库=============

    /**
     * 获取创建库语句
     * @param dataSourceName
     */
    @Override
    public String buildCreateDataSourceSql(String dataSourceName) {
        return DDLConstant.CREATE_DATA_SOURCE.format(dataSourceName);
    }

    /**
     * 获取删库语句
     * @param dataSourceName
     */
    @Override
    public String buildDropDataSourceSql(String dataSourceName) {
        return DDLConstant.DROP_DATA_SOURCE.format(dataSourceName);
    }

    /**
     * 获取创建表语句
     * @throws SQLException
     */
    @Override
    public String buildCreateTableSql(TableCM table) {
        HashMap<String,String> map = new HashMap<>();
        List<ColumnCM> columns = table.getColumns();
        map.put("tableName",table.getName());

        // 添加列:
        String colTemp = "`{columnName}` {columnType} {columnIsNull} {columnDefaultValue},";
        StringBuilder columnStr = new StringBuilder();
        columns.forEach(column->{
            Map<String,String> colMap = new HashMap<>();
            colMap.put("columnName",column.getName());
            colMap.put("columnType",column.getType());
            // if (Arrays.asList(ColumnTypeCompare.TEXTAREA,ColumnTypeCompare.RICH_TEXT).contains(column.getColumnTypeCompare())){
            //     colMap.put("columnIsNull","NOT NULL");// TEXT长文本可以设置为允许为空，数据库需要不能为空，保证旧数据有零值
            // }else {
            colMap.put("columnIsNull",column.getNullEnableFlag()?"NULL":"NOT NULL");
            // }


            if (column.getDefaultValueMode().equals("null")) {
                colMap.put("columnDefaultValue", "");
            }else if (StrUtil.containsAny(column.getType().toUpperCase(),"JSON","TEXT")){
                colMap.put("columnDefaultValue","");
            }else if (column.getDefaultValueMode().equals("expression")){
                // 时间的默认值函数不加单引号：
                // map.put("columnDefaultValue", column.getDefaultValue() != null?"DEFAULT "+ column.getDefaultValue():"");
                colMap.put("columnDefaultValue", "DEFAULT "+ column.getDefaultValue());
            }else if (MysqlColumnType.BOOLEAN.equals(column.getColumnTypeCompare())) {
                colMap.put("columnDefaultValue", column.getDefaultValue() != null?"DEFAULT "+ column.getDefaultValue():"");
            }else {
                colMap.put("columnDefaultValue", column.getDefaultValue() != null?"DEFAULT '"+ column.getDefaultValue()+"'":"");
            }
            columnStr.append(StrUtil.format(colTemp,colMap));
        });
        map.put("columns",columnStr.toString());
        String sqlTemp = "CREATE TABLE IF NOT EXISTS `{tableName}` ( " +
                "{columns} "+
                "PRIMARY KEY (`id`) "+
                ") ENGINE = InnoDB DEFAULT CHARSET = " + DDLConstant.DEFAULTCHARSET + " COLLATE = " + DDLConstant.DEFAULTCOLLATE + ";";


        return StrUtil.format(sqlTemp, map);
    }

    /**
     * 修改表名
     *
     * @return
     */
    @Override
    public String buildRenameTableSql(TableCM table) {
        return "ALTER TABLE `"+table.getOldName()+"` RENAME `"+table.getName()+"`;";
    }

    /**
     * 获取删表语句
     *
     * @param table
     * @throws SQLException
     */
    @Override
    public String buildDropTableSql(TableCM table) {
        return "DROP TABLE IF EXISTS `" + table.getName()+"`"+";";
    }

    /**
     * 获取删字段语句
     * @throws SQLException
     */
    @Override
    public String buildDropColumnSql(ColumnCM columnCM) {
        String finalSql;
        if (MysqlColumnType.DATE_RANGE.equals(columnCM.getColumnTypeCompare())){
            finalSql= "ALTER TABLE `"+ columnCM.getTableName()+"` " +
                    "DROP COLUMN `"+ columnCM.getName()+"`," +
                    "DROP COLUMN `"+ columnCM.getName()+"_stime`," +
                    "DROP COLUMN `"+ columnCM.getName()+"_etime`;";
        }else {
            finalSql = "ALTER TABLE `" + columnCM.getTableName() + "` DROP COLUMN `" + columnCM.getName() + "` "+";";
        }
        return finalSql;
    }

    /**
     * 获取创建列的语句
     *
     * @param column
     * @return
     */
    @Override
    public String buildCreateColumnSql(ColumnCM column) {
        HashMap<String,String> map = new HashMap<>();
        // map.put("targetSchema",metaData.getSchema());
        map.put("targetTableName", column.getTableName());
        map.put("targetColumnName", column.getName());
        map.put("sourceColumnType", column.getType());
        map.put("sourceColumnIsNull", column.getNullEnableFlag()?"NULL":"NOT NULL");
        // if (Arrays.asList(ColumnTypeCompare.TEXTAREA,ColumnTypeCompare.RICH_TEXT).contains(column.getColumnTypeCompare())){
        //     map.put("sourceColumnIsNull","NOT NULL");// TEXT长文本可以设置为允许为空，数据库需要不能为空，保证旧数据有零值
        // }else {
        map.put("sourceColumnIsNull",column.getNullEnableFlag()?"NULL":"NOT NULL");
        // }
        if (column.getDefaultValueMode().equals("null")){
            map.put("sourceColumnDefaultValue","");
        }else if (StrUtil.containsAny(column.getType().toUpperCase(),"JSON","TEXT")){
            map.put("sourceColumnDefaultValue","");
        }else if (column.getDefaultValueMode().equals("expression")){
            // 时间的默认值函数不加单引号：
            // map.put("columnDefaultValue", column.getDefaultValue() != null?"DEFAULT "+ column.getDefaultValue():"");
            map.put("sourceColumnDefaultValue", "DEFAULT "+ column.getDefaultValue());
        }else if (MysqlColumnType.BOOLEAN.equals(column.getColumnTypeCompare())) {
            map.put("sourceColumnDefaultValue", column.getDefaultValue() != null?"DEFAULT "+ column.getDefaultValue():"");
        }else {
            map.put("sourceColumnDefaultValue", column.getDefaultValue() != null?"DEFAULT '"+ column.getDefaultValue()+"'":"");
        }
        map.put("autoIncrement", column.getExtra().toUpperCase().contains("AUTO_INCREMENT")?"AUTO_INCREMENT":"");
        map.put("sourceColumnComment", column.getComment() != null?"COMMENT '"+ column.getComment()+"'":"");
        String dbtype = column.getType().toUpperCase();
        if (StrUtil.containsAny(column.getType().toUpperCase(),"VARCHAR","TEXT","LONGTEXT")){
            map.put("charsetVar", column.getCharsetVar());
        }else {
            map.put("charsetVar", "");
        }

        String finalSql;



        // 生成的sql的特殊处理：
        if (MysqlColumnType.DATE_RANGE.equals(column.getColumnTypeCompare())){
            // 时间范围(生成3个字段)
            /*
            `timerange` varchar(200) NOT NULL DEFAULT '00:00:00,00:00:05',
            `timerange_stime` time NOT NULL DEFAULT '00:00:00',
            `timerange_etime` time NOT NULL DEFAULT '00:00:05',
             */
            // 默认值处理
            String defaultValue = column.getDefaultValue();
            String defaultValueSTime = null;
            String defaultValueETime = null;
            if (StrUtil.isNotBlank(defaultValue) && defaultValue.contains(",")){
                String[] defaultValues = defaultValue.split(",");
                defaultValueSTime=defaultValues[0];
                defaultValueETime=defaultValues[1];
            }else if (StrUtil.isBlank(defaultValue)){// 兼容旧数据设置为零值，旧数据必须设置零值。
                if (column.getType().equals("DATETIME")){
                    defaultValueSTime="0001-01-01 00:00:00";
                    defaultValueETime="0001-01-01 00:00:00";
                }else if (column.getType().equals("DATE")){
                    defaultValueSTime="0001-01-01";
                    defaultValueETime="0001-01-01";
                }
            }

            /* 语法参考：
            ALTER TABLE `db1`.`student`
            ADD COLUMN `a` varchar(255) NULL,
            ADD COLUMN `b` varchar(255) NULL,
            ADD COLUMN `c` varchar(255) NULL;
            */

            map.put("sourceColumnDefaultValueStart", defaultValueSTime!=null?"DEFAULT '"+defaultValueSTime+"'":"");
            map.put("sourceColumnDefaultValueEnd", defaultValueETime!=null?"DEFAULT '"+defaultValueETime+"'":"");
            String sqlTemp ="ALTER TABLE `{targetTableName}` " +
                    "ADD COLUMN `{targetColumnName}` VARCHAR(200) {charsetVar} {sourceColumnIsNull} {sourceColumnDefaultValue} {sourceColumnComment},"+
                    "ADD COLUMN `{targetColumnName}_stime` {sourceColumnType} {sourceColumnIsNull} {sourceColumnDefaultValueStart},"+
                    "ADD COLUMN `{targetColumnName}_etime` {sourceColumnType} {sourceColumnIsNull} {sourceColumnDefaultValueEnd};";

            finalSql = StrUtil.format(sqlTemp,map);
        }else {
            String sqlTemp ="ALTER TABLE `{targetTableName}` ADD COLUMN `{targetColumnName}` {sourceColumnType} {charsetVar} {sourceColumnIsNull} " +
                    "{sourceColumnDefaultValue} {sourceColumnComment};";

            finalSql = StrUtil.format(sqlTemp, map, false);
        }
        return finalSql;
    }

    /**
     * 获取修改一个表的列顺序的语句(一条语句修改整个表的顺序)
     *
     * @return
     */
    @Override
    public String buildAlterColumnPosiSql(List<ColumnCM> sourceColumnOrders) {
        String tableName = sourceColumnOrders.isEmpty()?"":sourceColumnOrders.get(0).getTableName();
        // 正常算法生成位置语句：
        String modifyColumnTemp ="MODIFY COLUMN `{targetColumnName}` {sourceColumnType} {charsetVar} {sourceColumnIsNull} " +
                "{sourceColumnDefaultValue} {sourceColumnComment} {after}";

        /*ALTER TABLE `sort_test`
        MODIFY COLUMN `id1` int NOT NULL FIRST,
        MODIFY COLUMN `id3` int NULL DEFAULT NULL AFTER `id6`,
        MODIFY COLUMN `id9` int NULL DEFAULT NULL AFTER `id4`,
        MODIFY COLUMN `id8` int NULL DEFAULT NULL AFTER `id2`;*/

        ColumnCM recordTemp = null;
        List<String> recordSqlStrs = new ArrayList<>();
        for (int i = 0; i < sourceColumnOrders.size(); i++) {
            ColumnCM sourceColumn = sourceColumnOrders.get(i);
            Integer ordinalPosition = sourceColumn.getOrdinalPosition();
            if (i==0){
                // 如果是第一个，则直接将其记录为记录值recordName
                recordTemp = sourceColumn;
            }else if (ordinalPosition.compareTo(recordTemp.getOrdinalPosition())<0){
                Map<String,String> map = new HashMap<>();
                // 时间范围的判断：
                map.put("targetColumnName", sourceColumn.getName());
                map.put("sourceColumnType", sourceColumn.getType());
                // if (Arrays.asList(ColumnTypeCompare.TEXTAREA,ColumnTypeCompare.RICH_TEXT).contains(sourceColumn.getColumnTypeCompare())){
                //     map.put("sourceColumnIsNull","NOT NULL");// TEXT长文本可以设置为允许为空，数据库需要不能为空，保证旧数据有零值
                // }else {
                map.put("sourceColumnIsNull", sourceColumn.getNullEnableFlag()?"NULL":"NOT NULL");
                // }
                if (StrUtil.containsAny(sourceColumn.getType().toUpperCase(),"VARCHAR","TEXT","LONGTEXT")){
                    map.put("charsetVar", sourceColumn.getCharsetVar());
                }else {
                    map.put("charsetVar", "");
                }
                if (sourceColumn.getDefaultValueMode().equals("null")){
                    map.put("sourceColumnDefaultValue","");
                }else if (StrUtil.containsAny(sourceColumn.getType().toUpperCase(),"JSON","TEXT")){
                    map.put("sourceColumnDefaultValue","");
                }else if (sourceColumn.getDefaultValueMode().equals("expression")){
                    // 时间的默认值函数不加单引号：
                    // map.put("columnDefaultValue", column.getDefaultValue() != null?"DEFAULT "+ column.getDefaultValue():"");
                    map.put("sourceColumnDefaultValue", "DEFAULT "+ sourceColumn.getDefaultValue());
                }else if (MysqlColumnType.BOOLEAN.equals(sourceColumn.getColumnTypeCompare())) {
                    map.put("sourceColumnDefaultValue", sourceColumn.getDefaultValue() != null?"DEFAULT "+ sourceColumn.getDefaultValue():"");
                }else {
                    map.put("sourceColumnDefaultValue", sourceColumn.getDefaultValue() != null?"DEFAULT '"+ sourceColumn.getDefaultValue()+"'":"");
                }
                map.put("sourceColumnComment", sourceColumn.getComment() != null?"COMMENT '"+ sourceColumn.getComment()+"'":"");
                // map.put("after","AFTER `" + sourceColumnOrders.get(i-1).getName() +"`");


                // 多个字段的处理：
                if (MysqlColumnType.DATE_RANGE.equals(sourceColumn.getColumnTypeCompare())){
                    // 默认值处理
                    String defaultValue = sourceColumn.getDefaultValue();
                    String defaultValueSTime = null;
                    String defaultValueETime = null;
                    if (StrUtil.isNotBlank(defaultValue) && defaultValue.contains(",")){
                        String[] defaultValues = defaultValue.split(",");
                        defaultValueSTime=defaultValues[0];
                        defaultValueETime=defaultValues[1];
                    }else if (StrUtil.equals(defaultValue,"")){// 兼容旧数据设置为零值，旧数据必须设置零值。
                        if (sourceColumn.getType().equals("DATETIME")){
                            defaultValueSTime="0001-01-01 00:00:00";
                            defaultValueETime="0001-01-01 00:00:00";
                        }else if (sourceColumn.getType().equals("DATE")){
                            defaultValueSTime="0001-01-01";
                            defaultValueETime="0001-01-01";
                        }
                    }

                    // 第一个字段（name）
                    map.put("sourceColumnType", "VARCHAR(200)");
                    if (MysqlColumnType.DATE_RANGE.equals(sourceColumnOrders.get(i-1).getColumnTypeCompare())){
                        map.put("after","AFTER `" + sourceColumnOrders.get(i-1).getName() +"_etime`");
                    }else {
                        map.put("after","AFTER `" + sourceColumnOrders.get(i-1).getName() +"`");
                    }
                    recordSqlStrs.add(StrUtil.format(modifyColumnTemp, map));
                    // 第二个字段（name_stime）
                    map.put("sourceColumnType", sourceColumn.getType());
                    map.put("targetColumnName", sourceColumn.getName() +"_stime");
                    map.put("after","AFTER `" + sourceColumn.getName() +"`");
                    map.put("sourceColumnDefaultValue", defaultValueSTime!=null?"DEFAULT '"+defaultValueSTime+"'":"");
                    map.put("sourceColumnComment","");
                    recordSqlStrs.add(StrUtil.format(modifyColumnTemp, map));
                    // 第三个字段（name_etime）
                    map.put("sourceColumnType", sourceColumn.getType());
                    map.put("targetColumnName", sourceColumn.getName() +"_etime");
                    map.put("after","AFTER `" + sourceColumn.getName() +"_stime`");
                    map.put("sourceColumnDefaultValue", defaultValueETime!=null?"DEFAULT '"+defaultValueETime+"'":"");
                    map.put("sourceColumnComment","");
                    recordSqlStrs.add(StrUtil.format(modifyColumnTemp, map));
                }else {
                    // 前一个字段是多字段：
                    if (MysqlColumnType.DATE_RANGE.equals(sourceColumnOrders.get(i-1).getColumnTypeCompare())){
                        map.put("after","AFTER `" + sourceColumnOrders.get(i-1).getName() +"_etime`");
                    }else {
                        map.put("after","AFTER `" + sourceColumnOrders.get(i-1).getName() +"`");
                    }
                    String formatSql = StrUtil.format(modifyColumnTemp, map);
                    recordSqlStrs.add(formatSql);
                }
            }else {
                // 跳过记录，更新记录值
                recordTemp = sourceColumn;
            }
        }
        if (recordSqlStrs.isEmpty()){
            return null;
        }
        String modifyColumnSql = String.join(",", recordSqlStrs);


        /*ALTER TABLE `sort_test`
        MODIFY COLUMN `id1` int NOT NULL FIRST,
        MODIFY COLUMN `id3` int NULL DEFAULT NULL AFTER `id6`,
        MODIFY COLUMN `id9` int NULL DEFAULT NULL AFTER `id4`,
        MODIFY COLUMN `id8` int NULL DEFAULT NULL AFTER `id2`;*/

        String sqlTemp= "ALTER TABLE `{targetTableName}` {modifyColumnSql};";
        Map<String,String> map = new HashMap<>();
        map.put("targetTableName",tableName);
        map.put("modifyColumnSql",modifyColumnSql);
        return StrUtil.format(sqlTemp,map);
    }

    /**
     * 修改列信息
     * @param column
     * @return
     */
    @Override
    public List<String> buildAlterColumnSql(ColumnCM column) {
        String type = column.getType();
        Boolean nullEnableFlag = column.getNullEnableFlag();
        List<String> sqls = new ArrayList<>();
        column.setType(column.getOldType());
        if (!Objects.equals(nullEnableFlag, column.getOldNullEnableFlag()) && nullEnableFlag.equals(false)) {
            column.setNullEnableFlag(column.getOldNullEnableFlag());
        }
        sqls.add(buildAlterColumnSqlInternal(column));
        column.setOldName(column.getName());
        if (!Objects.equals(nullEnableFlag, column.getOldNullEnableFlag()) && nullEnableFlag.equals(false)) {
            column.setType(column.getOldType());
            column.setNullEnableFlag(nullEnableFlag);
            sqls.add(buildAlterColumnSqlInternal(column));
        }
        if (!Objects.equals(type, column.getOldType())) {
            column.setType(type);
            if (!Objects.equals(nullEnableFlag, column.getOldNullEnableFlag()) && nullEnableFlag.equals(false)) {
                column.setNullEnableFlag(column.getOldNullEnableFlag());
            }
            sqls.add(buildAlterColumnSqlInternal(column));
        }
        column.setType(type);
        column.setNullEnableFlag(nullEnableFlag);
        sqls.add(buildAlterColumnSqlInternal(column));
        return sqls;
    }

    private String buildAlterColumnSqlInternal(ColumnCM column) {
        Map<String,String> map = new HashMap<>();
        map.put("tableName",column.getTableName());
        map.put("oldColumnName",column.getOldName());
        map.put("columnName",column.getName());
        map.put("columnType",column.getType());
        if (StrUtil.containsAny(column.getType().toUpperCase(),"VARCHAR","TEXT","LONGTEXT")){
            map.put("charsetVar", column.getCharsetVar());
        }else {
            map.put("charsetVar", "");
        }
        // if (Arrays.asList(ColumnTypeCompare.TEXTAREA,ColumnTypeCompare.RICH_TEXT).contains(column.getColumnTypeCompare())){
        //     map.put("columnIsNull","NOT NULL");// TEXT长文本可以设置为允许为空，数据库需要不能为空，保证旧数据有零值
        // }else {
        map.put("columnIsNull",column.getNullEnableFlag()?"NULL":"NOT NULL");
        // }
        if (column.getDefaultValueMode().equals("null")){
            map.put("columnDefaultValue","");
        }else if (StrUtil.containsAny(column.getType().toUpperCase(),"JSON","TEXT")){
            map.put("columnDefaultValue","");
        }else if (column.getDefaultValueMode().equals("expression")){
            // 时间的默认值函数不加单引号：
            // map.put("columnDefaultValue", column.getDefaultValue() != null?"DEFAULT "+ column.getDefaultValue():"");
            map.put("columnDefaultValue", "DEFAULT "+ column.getDefaultValue());
        }else if (MysqlColumnType.BOOLEAN.equals(column.getColumnTypeCompare())) {
            map.put("columnDefaultValue", column.getDefaultValue() != null?"DEFAULT "+ column.getDefaultValue():"");
        }else {
            map.put("columnDefaultValue", column.getDefaultValue() != null?"DEFAULT '"+ column.getDefaultValue()+"'":"");
        }
        map.put("columnComment", column.getComment() != null?"COMMENT '"+ column.getComment()+"'":"");

        String finalSql;

        // 时间范围特殊处理
        if (MysqlColumnType.DATE_RANGE.equals(column.getColumnTypeCompare())){
            // 默认值处理
            String defaultValue = column.getDefaultValue();
            String defaultValueSTime = null;
            String defaultValueETime = null;
            if (StrUtil.isNotBlank(defaultValue) && defaultValue.contains(",")){
                String[] defaultValues = defaultValue.split(",");
                defaultValueSTime=defaultValues[0];
                defaultValueETime=defaultValues[1];
            }else if (StrUtil.equals(defaultValue,"")){// 兼容旧数据设置为零值，旧数据必须设置零值。
                if (column.getType().equals("DATETIME")){
                    defaultValueSTime="0001-01-01 00:00:00";
                    defaultValueETime="0001-01-01 00:00:00";
                }else if (column.getType().equals("DATE")){
                    defaultValueSTime="0001-01-01";
                    defaultValueETime="0001-01-01";
                }
            }

            map.put("columnDefaultValueStart", defaultValueSTime!=null?"DEFAULT '"+defaultValueSTime+"'":"");
            map.put("columnDefaultValueEnd", defaultValueETime!=null?"DEFAULT '"+defaultValueETime+"'":"");

            String sqlTemp = "ALTER TABLE `{tableName}` "+
                    "CHANGE COLUMN `{oldColumnName}` `{columnName}` varchar(200) {charsetVar} {columnIsNull} {columnDefaultValue} {columnComment},"+
                    "CHANGE COLUMN `{oldColumnName}_stime` `{columnName}_stime` {columnType} {columnIsNull} {columnDefaultValueStart}," +
                    "CHANGE COLUMN `{oldColumnName}_etime` `{columnName}_etime` {columnType} {columnIsNull} {columnDefaultValueEnd};";

            finalSql = StrUtil.format(sqlTemp, map,false);
        }else {
            String sqlTemp = "ALTER TABLE `{tableName}` CHANGE COLUMN `{oldColumnName}` `{columnName}` {columnType} {charsetVar} {columnIsNull} {columnDefaultValue} {columnComment};";
            finalSql = StrUtil.format(sqlTemp,map,false);
        }

        return finalSql;
    }

    /**
     * 获取创建索引的语句
     * @param index
     * @return
     */
    @Override
    public String buildCreateIndex(IndexCM index) {
        HashMap<String,String> map = new HashMap<>();
        map.put("tableName", index.getTableName());
        map.put("indexType", index.getUniqueFlag()?"UNIQUE INDEX":"INDEX");
        map.put("indexName",index.getIndexName());
        map.put("columnNames", index.getAssembColumnNames());
        String sqlTemp = "ALTER TABLE `{tableName}` ADD {indexType} `{indexName}` ({columnNames});";
        return StrUtil.format(sqlTemp,map);
    }



    /**
     * 索引修改
     * @param index
     * @return
     */
    @Override
    public String buildAlterIndex(IndexCM index) {
        Map<String,String> map = new HashMap<>();
        map.put("tableName",index.getTableName());
        map.put("indexType", index.getUniqueFlag()?"UNIQUE INDEX":"INDEX");
        map.put("oldName",index.getOldName());
        map.put("indexName",index.getIndexName());
        map.put("columnNames",index.getAssembColumnNames());
        String alterSql = "ALTER TABLE `{tableName}` DROP INDEX `{oldName}`,ADD {indexType} `{indexName}`({columnNames}) USING BTREE;";
        return StrUtil.format(alterSql,map);
    }

    /**
     * 删除该索引
     * @return
     */
    @Override
    public String buildDropIndex(IndexCM index) {
        return "ALTER TABLE `"+index.getTableName()+"` DROP INDEX `"+index.getIndexName()+"`"+";";
    }


}
